package com.article.controller.system;

import com.article.dto.ReturnError;
import com.article.enums.ReturnInfoEnum;
import com.article.model.AdminInfo;
import com.article.model.RoleInfo;
import com.article.service.AdminInfoService;
import com.article.service.RoleInfoService;
import com.article.utils.MD5;
import com.article.utils.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created by Administrator on 2017/5/3.
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    private final static MD5 md5 = new MD5();
    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private AdminInfoService adminInfoService;
    @Autowired
    private RoleInfoService roleInfoService;

    /**
     * 用户修改密码
     *
     * @param oldpassword
     * @param password
     * @return
     */
    @RequestMapping(value = "/updPsd", method = RequestMethod.POST)
    public ReturnError updPsd(String oldpassword, String password) {
        if (StringUtil.isEmpty(oldpassword)) {
            return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入旧密码");
        }
        if (StringUtil.isEmpty(password)) {
            return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入新密码");
        }
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        AdminInfo adminInfo = (AdminInfo) session.getAttribute("adminLogin"), oldAdminInfo = null;
        try {
            if (adminInfo == null) {
                return new ReturnError(true, ReturnInfoEnum.NOSESSION.getType(), ReturnInfoEnum.NOSESSION.getInfo(),
                        "login.html");
            }
            oldAdminInfo = adminInfoService.getById(adminInfo.getId());
            oldpassword = md5.getMD5ofStr(oldpassword);
            if (!oldpassword.equals(oldAdminInfo.getPassword())) {
                return new ReturnError(true, ReturnInfoEnum.FAIL.getType(), "旧密码错误", "login.html");
            }
            password = md5.getMD5ofStr(password);
            oldAdminInfo.setPassword(password);
            oldAdminInfo.setGmtModified(Calendar.getInstance().getTime());
            adminInfoService.updateLogin(oldAdminInfo);
            session.setAttribute("adminLogin", oldAdminInfo);
            return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), ReturnInfoEnum.SUCCESS.getInfo(), null);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getType(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 管理员列表
     *
     * @param key
     * @param pageIndex
     * @param limit
     * @return
     */
    @RequestMapping(value = "/listAdmin", method = RequestMethod.POST)
    public ReturnError listAdmin(@RequestParam(name = "key", required = false) String key,
                                 @RequestParam(name = "pageIndex", required = true, defaultValue = "0") Integer pageIndex,
                                 @RequestParam(name = "limit", required = true, defaultValue = "10") Integer limit) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (StringUtil.isNotEmpty(key)) {
                map.put("accountLike", key);
            }
            List<AdminInfo> adminInfoList = new ArrayList<AdminInfo>();
            PageHelper.startPage(pageIndex + 1, limit);
            adminInfoList = adminInfoService.listByPage(map);
            RoleInfo roleInfo = null;
            for (AdminInfo adminInfo : adminInfoList) {
                roleInfo = roleInfoService.getById(adminInfo.getRoleId());
                adminInfo.setRoleInfo(roleInfo);
            }
            PageInfo<AdminInfo> p = new PageInfo<AdminInfo>(adminInfoList);
            return new ReturnError(false, null, p.getTotal(), p.getList());
        } catch (Exception e) {
            return new ReturnError(true, ReturnInfoEnum.ERROR.getInfo(), 0L, null);
        }
    }

    /**
     * 新增账号
     *
     * @param adminInfo
     * @return
     */
    @RequestMapping(value = "/saveAdmin", method = RequestMethod.POST)
    public ReturnError saveAdmin(AdminInfo adminInfo) {
        try {
            if (StringUtil.isEmpty(adminInfo.getAccount())) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入账号", null);
            }
            if (StringUtil.isEmpty(adminInfo.getNickName())) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入昵称", null);
            }
            if (StringUtil.isEmpty(adminInfo.getPassword())) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入密码", null);
            }
            adminInfo.setPassword(md5.getMD5ofStr(adminInfo.getPassword()));
            adminInfo.setGmtCreate(Calendar.getInstance().getTime());
            adminInfo.setGmtModified(adminInfo.getGmtCreate());
            return adminInfoService.saveAdmin(adminInfo);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getType(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 修改账户
     *
     * @param id
     * @param account
     * @param password
     * @return
     */
    @RequestMapping(value = "/updateAdmin", method = RequestMethod.POST)
    public ReturnError updateAdmin(@RequestParam(name = "id", required = true) Long id,
                                   @RequestParam(name = "account", required = true) String account,
                                   @RequestParam(name = "password", required = true) String password,
                                   @RequestParam(name = "nickName", required = true) String nickName,
                                   @RequestParam(name = "roleId", required = true) Long roleId) {
        try {
            if (StringUtil.isEmpty(account)) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入账号", null);
            }
            if (StringUtil.isEmpty(nickName)) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入昵称", null);
            }
            if (StringUtil.isEmpty(password)) {
                return new ReturnError(true, ReturnInfoEnum.EMPTY.getType(), "请输入密码", null);
            }
            AdminInfo adminInfo = adminInfoService.getById(id);
            if (adminInfo == null) {
                return new ReturnError(true, ReturnInfoEnum.NORECORD.getType(), ReturnInfoEnum.NORECORD.getInfo(), null);
            }
            if (!password.equals(adminInfo.getPassword())) {
                password = md5.getMD5ofStr(password);
                adminInfo.setPassword(password);
            }
            adminInfo.setRoleId(roleId);
            adminInfo.setAccount(account);
            adminInfo.setNickName(nickName);
            adminInfo.setGmtModified(Calendar.getInstance().getTime());
            return adminInfoService.updateAdmin(adminInfo);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getType(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 删除账户
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/removeAdmin", method = RequestMethod.POST)
    public ReturnError removeAdmin(@RequestParam(name = "ids", required = true) String ids) {
        try {
            return adminInfoService.removeAdmin(ids);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getType(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 管理员列表页面角色集合
     *
     * @return
     */
    @RequestMapping(value = "/listRoles", method = RequestMethod.POST)
    public ReturnError listRoles() {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<RoleInfo> roleInfoList = new ArrayList<RoleInfo>();
            roleInfoList = roleInfoService.listByPage(map);
            return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), roleInfoList);
        } catch (Exception e) {
            logger.info(ReturnInfoEnum.ERROR.getType(), e);
            return new ReturnError(true, ReturnInfoEnum.ERROR.getType(), ReturnInfoEnum.ERROR.getInfo(), null);
        }
    }
}
